import 'package:flutter_pink_app/business/token.dart';
import 'base/request.dart';
import 'base/adapter.dart';
import 'base/response.dart';
import 'base/error.dart';

class NetworkCall {
  static NetworkCall _singleInstance; // 默认单例
  NetworkCall({BaseAdapter adapter}) : _adapter = adapter;
  // 单例工厂构造函数
  factory NetworkCall.getInstance({BaseAdapter adapter}) {
    if (_singleInstance == null) {
      _singleInstance = NetworkCall(adapter: adapter);
    }
    return _singleInstance;
  }

  BaseAdapter _adapter;

  // 设置当前适配器
  void setAdapter(BaseAdapter adapter) {
    _adapter = adapter;
  }

  // 发送方法
  Future<BaseResponse<T>> send<T>(BaseRequest req) async {
    // 实质上是去调用适配器的send方法
    BaseResponse<T> res;
    // 检查是否需要token，并写入
    if (req.needLogin) {
      String token = await getToken();
      req.setHeader(token, uniqueToken);
    }
    try {
      res = await _adapter.send(req);
    } on BaseNetworkError catch (e) {
      e.expectedErrorLog();
      _checkStatuscodeError(e);
    } catch (error) {
      print('请求的过程中发生了未知的错误');
      print(StackTrace.current);
    }
    print('得到请求数据：${res.message}, ${res.data}');
    return res;
  }

  // 检查状态码
  void _checkStatuscodeError(BaseNetworkError err) {
    if (err.statusCode == 401) {
      throw LogoutError(err.data);
    } else if (err.statusCode == 403) {
      throw UnauthError(err.data);
    } else {
      throw err; // 抓不到就往上冒泡
    }
  }
}
